package http_transport

import (
	"context"
	"fmt"
	"io"
	"net/http"
	"strings"
	"time"
)

var (
	tp = &http.Transport{
		DisableKeepAlives:   true,
		MaxIdleConns:        100,
		MaxIdleConnsPerHost: 10,
		MaxConnsPerHost:     2,
		IdleConnTimeout:     10 * time.Second,
	}
)

type client struct {
	clt *http.Client
}

func NewClient() (*client, error) {
	return &client{clt: &http.Client{Transport: tp}}, nil
}

//获取头部cookie
func GetHeaderCookie(header http.Header, cookieName string, cookie *string) {
	if cookies, ok := header["Set-Cookie"]; ok {
		for _, ck := range cookies {
			if strings.Contains(ck, cookieName) {
				//// 定义正则表达式
				//re := regexp.MustCompile(`=\w+?;`)
				//// 使用正则表达式查找匹配项
				//match := re.FindString(ck)

				// 通过字符串函数查找 cookieName 的位置
				startIndex := strings.Index(ck, fmt.Sprintf("%s=", cookieName))
				if startIndex == -1 {
					return
				}
				// 在 cookieName= 后查找第一个分号的位置
				endIndex := strings.Index(ck[startIndex:], ";")
				if endIndex == -1 {
					return
				}
				// 从 startIndex去除cookieName本身长度的地方 开始截取 endIndex 长度的字符串
				match := ck[startIndex+len(cookieName)+1 : startIndex+endIndex]
				//fmt.Printf("match:%s\n", match)
				*cookie = match
				return
			}
		}
	}
}
func (c *client) RoundTrip(ctx context.Context, body io.Reader) (*http.Response, error) {
	// http://127.0.0.1/dac?action=%s&apikey=%s
	url := ctx.Value("url").(string)
	method := ctx.Value("method").(string)

	r, err := http.NewRequest(method, url, body)
	if err != nil {
		return nil, err
	}

	//r.Header.Add("Content-Type", "application/x-www-form-urlencoded; charset=utf-8")
	if ctx.Value("Header") != nil {
		if v, ok := ctx.Value("Header").(http.Header); ok {
			r.Header = v
		}
	}
	//r.Header.Set("Content-Type", ctx.Value("Content-Type").(string))
	resp, err := c.clt.Do(r.WithContext(ctx))
	c.clt.CloseIdleConnections() //如果不调用这个的话，会一直报Unsolicited response received on idle HTTP channel starting with "\r\n\r\n"; err=<nil> 有兴趣可以去看源码
	if err != nil {
		return nil, err
	}

	return resp, nil
}

func (c *client) Close() error {
	c.clt.CloseIdleConnections()
	return nil
}
